import React, { useState,useEffect } from'react'
import '@/assets/css/gouwuche.scss'
import {MyButton,MyRate} from '@/components/copyAntDesign'
function Gouwuche() {
  const [list, setList] = useState([])
  const [allTotal, setAllTotal] = useState(0)
  const [rate, setRate] = useState(5)
  useEffect(() => {
    fetch('/gouwuche.json')
        .then(res =>res.json())
        .then(data => {
          console.log(data)
          setList(data.list)
        })
  },[])
  useEffect(()=>{
    setAllTotal(computeTotal())
  },[list])
  const handleAdd = (index) => {
      return () => {
        list[index].count++
        setList([...list])
      }
  }
  const handleDel = (index) => {
      return () =>{
          if (list[index].count > 1){
              list[index].count--
          }
          setList([...list])
    }
  }
  const handleActived = (index) => {
    return () => {
        list[index].isActived = !list[index].isActived
        setList([...list])
    }
  }
  const computeTotal = () => {
      return parseFloat(list.reduce((acc, cur) => {
          return cur.isActived ? acc + cur.count * cur.price : acc
      }, 0).toFixed(2))
  }
  return (
    <>
      <h1>购物车</h1>
      <div className="cart-list">
        {
          list.map((item, index) => {
            return <Item key={index} {...item} id={index} handleAdd={handleAdd} handleDel={handleDel} handleActived={handleActived} />
          })
        }
      </div>
      <div className="cart-total">总计: ￥{allTotal}</div>
        <h1>仿照 ant design 组件</h1>
        <MyButton type="primary">primary</MyButton>
        <MyButton size="small" >default</MyButton>
        <MyButton type="primary" danger>dashed</MyButton>
        <MyButton icon={<Icon />}>icon</MyButton>
        <MyRate count={5} value={rate} onChange={setRate} >A</MyRate>{rate}
    </>
  )
}
function Item(props){
  const {title, price, count,isActived,id,handleDel,handleAdd,handleActived} = props
  return (
      <div className="cart-item">
        <h5>商品名称:{title}</h5>
        <div>单价: ￥{price}</div>
        <p>数量: <span onClick={handleDel(id)}> - </span> {count} <span onClick={handleAdd(id)}> + </span></p>
        <button onClick={handleActived(id)}>{isActived ? '已选中' : '加入购物车'}</button>
      </div>
  )
}

function Icon(props){
    return (
        <span>😍</span>
    )
}

export default Gouwuche;

